package com.lry.jvm.rtda;

import com.lry.jvm.util.Util;

public class OperandStack {

    private int size;
    private int maxStack;
    private Slot[]slots;

    public OperandStack(int maxStack) {
        this.maxStack = maxStack;
        if (maxStack > 0) {
            slots = new Slot[maxStack];
        }
//        else{
//            Util.panic("stack <= 0");
//        }
    }

    public void pushSlot(Slot slot) {
        if (size >= maxStack) {
            Util.panic("操作数栈溢出异常");
        }
        slots[size++] = slot;
    }

    public Slot popSlot()  {
        if (size <= 0) {
            Util.panic("操作数栈溢出异常");
        }
        return slots[--size];
    }

    public void pushInt(int val)  {
        pushSlot(Util.setInt(val));
    }

    public int popInt() {
        return Util.getInt(popSlot());
    }

    public void pushFloat(float val) {
        int a = Float.floatToIntBits(val);
        pushInt(a);
    }

    public float popFloat() {
        return Float.intBitsToFloat(popInt());
    }

    public void pushLong(long val) {
        Slot[] slots = Util.setLong(val);
        pushSlot(slots[0]);
        pushSlot(slots[1]);
    }

    public long popLong()  {
        Slot low = popSlot();
        Slot high = popSlot();
        return Util.getLong(new Slot[]{high, low});
    }

    public void pushDouble(double val)  {
        pushLong(Double.doubleToLongBits(val));
    }

    public double popDouble()   {
        return Double.longBitsToDouble(popLong());
    }

    public void pushRef(JObject ref)  {
        Slot slot = new Slot();
        slot.setRef(ref);
        pushSlot(slot);
    }

    public JObject popRef()   {
        JObject ref = popSlot().getRef();
        return ref;
    }


    public JObject getRefFromTop(int n) {
        return slots[size-1-n].getRef();
    }

    public void pushBoolean(boolean b) {
        if(b){
            pushInt(1);
        }else{
            pushInt(0);
        }
    }

    public boolean popBoolean(){
        int i = popInt();
        return i==1?true:false;
    }
}
